//
//  DetailTravelViewController.m
//  EDPS
//
//  Created by 张维扬 on 15/11/27.
//  Copyright © 2015年 张维扬. All rights reserved.
//

#import "DetailTravelViewController.h"
#import "RouteScheduleTableViewCell.h"
#import "ZWY_NetHandle.h"
#import "ExploreModel.h"
#import "DetailTravelTableViewCell.h"
#import "Masonry.h"
#import "MBProgressHUD.h"
#import "DetailTravelModel.h"
#import "TravelMapViewController.h"
#import "UIImageView+WebCache.h"
#import "PicSeeCollectionViewCell.h"
@interface DetailTravelViewController ()<UITableViewDataSource, UITableViewDelegate, pushToMapDelegate, UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *covered_countries_Arr;//国旗数据
@property (nonatomic, strong) UIImageView *headPic;
@property (nonatomic, strong) NSArray *citiesArr; // 城市数组
@property (nonatomic, strong) NSMutableArray *waypointsArr;// 行程数据
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) NSMutableArray *photoSizeArr; // 图片尺寸
@property (nonatomic, strong) NSMutableArray *userArr;//用户
@property (nonatomic, strong) UIView *headerView;
@property (nonatomic, strong) NSMutableArray *daysArr;
@property (nonatomic, strong) MBProgressHUD *HUD;
@property (nonatomic, strong) NSMutableArray *picSeeArr;
@property (nonatomic, assign) NSInteger index;
@end

@implementation DetailTravelViewController
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.view.backgroundColor = RGBA(253, 244, 233, 1);
    self.navigationItem.hidesBackButton = YES;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor blackColor];
    self.navigationController.navigationBarHidden = NO;
    
    // 左面按钮
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    backBtn.frame = CGRectMake(1, 1, ScreenWidth / 75 * 5, ScreenWidth / 75 * 5);
    [backBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-back"] forState:UIControlStateNormal];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [backBtn addTarget:self action:@selector(backBtn_action) forControlEvents:UIControlEventTouchUpInside];
    
    // 菊花
    self.HUD = [[MBProgressHUD alloc]initWithView:self.view];
    self.HUD.alpha = 0.5;
    [self.view addSubview:self.HUD];
    [self.HUD show:YES];
    // 请求数据
    [self getData];
 
}
- (void)backBtn_action
{
    self.collectionView.alpha = 0;
    [self.navigationController popViewControllerAnimated:YES];
}
#pragma mark - 请求数据
- (void)getData
{
    NSString *url = [NSString stringWithFormat:@"http://api.breadtrip.com/trips/%@/", self.idModel.travel_id.stringValue];
    NSLog(@"%@", url);
    [ZWY_NetHandle getURL:url Cookie:nil parameter:nil result:^(id result) {
        if (result != nil) {
            // 创建图片查看view
            [self createCollectionView];
            // 创建tableView
            [self createTableView];
        }
        // 获取用户数据
        [self.headPic sd_setImageWithURL:[NSURL URLWithString:result[@"trackpoints_thumbnail_image"]] placeholderImage:[UIImage imageNamed:@"hold"]];
        // 获取国旗数据
        self.covered_countries_Arr = [DetailTravelModel transformWithArray:result[@"covered_countries"]];
        // 获取城市数组
        self.citiesArr = result[@"cities"];
        // 获取旅游行程数据
        self.waypointsArr = [NSMutableArray array];
        NSMutableArray *tempArr = [NSMutableArray array];
        for (NSDictionary *dic in result[@"days"]) {
            [tempArr addObject: dic[@"waypoints"]];
        }
        NSMutableArray *waypointsTempArr = [NSMutableArray array];
        for (NSArray *arr in tempArr) {
            waypointsTempArr = [DetailTravelModel transformWithArray:arr];
            [self.waypointsArr addObject:waypointsTempArr];
        }
        NSLog(@"%@", self.waypointsArr);
        // 图片查看数据
        self.picSeeArr = [NSMutableArray array];
        NSMutableArray *tempPicSeeArr = [NSMutableArray array];
        for (NSDictionary *dic in result[@"days"]) {
            for (NSDictionary *dic1 in dic[@"waypoints"]) {
                [tempPicSeeArr addObject:dic1];
            }
        }
        self.picSeeArr = [DetailTravelModel transformWithArray:tempPicSeeArr];
        // 获取具体天数
        self.daysArr = [DetailTravelModel transformWithArray:result[@"days"]];
        
        [self.tableView reloadData];
        [self.collectionView reloadData];
    }];
}
#pragma mark - 创建collectionView图片查看
- (void)createCollectionView
{
    // 创建图片浏览视图
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    // 设置滑动方向为横滑
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    layout.itemSize = CGSizeMake(ScreenWidth, ScreenHeight);
    layout.minimumInteritemSpacing = 0;
    layout.minimumLineSpacing = 0;
    
    self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) collectionViewLayout:layout];
    self.collectionView.backgroundColor = [UIColor blackColor];
    self.collectionView.dataSource = self;
    self.collectionView.delegate = self;
    self.collectionView.pagingEnabled = YES;
    [self.collectionView registerClass:[PicSeeCollectionViewCell class] forCellWithReuseIdentifier:@"picSeeCell"];
    [self.view addSubview:self.collectionView];
}
#pragma mark - 创建tableView
- (void)createTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
//    self.tableView.contentInset = UIEdgeInsetsMake(ScreenWidth * 0.5, 0, 0, 0);
    self.tableView.bounces = YES;
    self.tableView.separatorStyle = UITableViewCellAccessoryNone;
    self.tableView.backgroundColor = RGBA(253, 244, 233, 1);
    [self.view addSubview:self.tableView];
    [self.tableView registerClass:[RouteScheduleTableViewCell class] forCellReuseIdentifier:@"routeCell"];
    [self.tableView registerClass:[DetailTravelTableViewCell class] forCellReuseIdentifier:@"detailCell"];
    
    // 头像
//    self.headPic = [[UIImageView alloc] initWithFrame:CGRectMake(0, -ScreenWidth * 0.5, ScreenWidth, ScreenWidth * 0.5)];
//    self.headPic.clipsToBounds = YES;
//    self.headPic.contentMode = UIViewContentModeScaleAspectFill;
//    [self.tableView addSubview:self.headPic];
    
}
-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    // 下拉放大
    CGPoint offset = scrollView.contentOffset;
    if (offset.y < 0) {
        CGRect rect = self.headPic.frame;
        rect.origin.y = offset.y;
        rect.size.height =  -offset.y;
        self.headPic.frame = rect;
    }
}
#pragma mark - tableView协议方法
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        RouteScheduleTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"routeCell"];
        cell.backgroundColor = RGBA(253, 244, 233, 1);
        if (self.covered_countries_Arr.count != 0) {
            cell.model = self.covered_countries_Arr[indexPath.row];
        }
        // 传城市数组
        cell.citiesArr = self.citiesArr;
        // 传送数组个数
        cell.covered_countries_Counts = self.covered_countries_Arr.count;
        return cell;
        
    }else{
        DetailTravelTableViewCell *detail = [tableView dequeueReusableCellWithIdentifier:@"detailCell"];
        detail.backgroundColor = RGBA(253, 244, 233, 1);
        [detail setSelectionStyle:UITableViewCellSelectionStyleNone];
        // 签跳转地图代理人属性
        detail.mapDelegate = self;
        detail.model = self.waypointsArr[indexPath.section - 1][indexPath.row];
        return detail;
    }
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return nil;
    }else{
        if (section == 1) {
            UIView *sectionView = [[UIView alloc] initWithFrame:CGRectZero];
            // 时间轴的第一张图片
            UIImageView *img = [[UIImageView alloc] init];
            [sectionView addSubview:img];
            //        img.backgroundColor = [UIColor redColor];
            img.image = [UIImage imageNamed:@"journey_table_header"];
            [img mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(sectionView.mas_left).offset(ScreenWidth * 0.04);
                make.bottom.mas_equalTo(sectionView.mas_bottom).offset(0);
                make.size.mas_equalTo(CGSizeMake(ScreenWidth, 40));
            }];
            // 具体时间
            UILabel *dayLabel = [[UILabel alloc] init];
            dayLabel.textColor = RGBA(152, 119, 89, 1);
            [dayLabel setFont:[UIFont systemFontOfSize:13]];
            [sectionView addSubview:dayLabel];
            [dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(img.mas_top).offset(0);
                make.left.mas_equalTo(sectionView).offset(55);
                make.size.mas_equalTo(CGSizeMake(ScreenWidth - 55, 20));
            }];
            
            NSString *month = [[(DetailTravelModel *) self.daysArr[section - 1] date] substringWithRange:NSMakeRange(5, 2)];
            NSString *day = [[(DetailTravelModel *) self.daysArr[section - 1] date] substringWithRange:NSMakeRange(8, 2)];
            dayLabel.text = [NSString stringWithFormat:@"第%@天 %@月%@日", [(DetailTravelModel *) self.daysArr[section - 1] day], month, day];
            return sectionView;
        }else{
            UIView *sectionView = [[UIView alloc] initWithFrame:CGRectZero];
            // 时间轴的第一张图片
            UIImageView *img = [[UIImageView alloc] init];
            [sectionView addSubview:img];
            //        img.backgroundColor = [UIColor redColor];
            img.image = [UIImage imageNamed:@"journey_section_header"];
            [img mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.mas_equalTo(sectionView.mas_left).offset(ScreenWidth * 0.04);
                make.bottom.mas_equalTo(sectionView.mas_bottom).offset(0);
                make.size.mas_equalTo(CGSizeMake(ScreenWidth, 40));
            }];
            // 具体时间
            UILabel *dayLabel = [[UILabel alloc] init];
            dayLabel.textColor = RGBA(152, 119, 89, 1);
            [dayLabel setFont:[UIFont systemFontOfSize:13]];
            [sectionView addSubview:dayLabel];
            [dayLabel mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.mas_equalTo(img.mas_top).offset(0);
                make.left.mas_equalTo(sectionView).offset(55);
                make.size.mas_equalTo(CGSizeMake(ScreenWidth - 55, 20));
            }];
            
            NSString *month = [[(DetailTravelModel *) self.daysArr[section - 1] date] substringWithRange:NSMakeRange(5, 2)];
            NSString *day = [[(DetailTravelModel *) self.daysArr[section - 1] date] substringWithRange:NSMakeRange(8, 2)];
            dayLabel.text = [NSString stringWithFormat:@"第%@天 %@月%@日", [(DetailTravelModel *) self.daysArr[section - 1] day], month, day];
            return sectionView;
        }
    }
}
#pragma mark - 分区数
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.waypointsArr.count + 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (section == 0) {
        return 1;
    }else{
        return [self.waypointsArr[section - 1] count];
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    if (section == 0) {
        return 0;
    }
    else{
        if (section == 1) {
            return 50;
        }else{
            return 22;
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        if (self.covered_countries_Arr.count != 0) {
            return ScreenWidth * 0.2;
        }else{
            return ScreenWidth * 0.02;
        }
    }
    else{
        // 计算图片高度
        DetailTravelModel *tempModel = self.waypointsArr[indexPath.section - 1][indexPath.row];
        CGFloat imgH = (tempModel.h).integerValue;
        CGFloat imgW = (tempModel.w).integerValue;
        // 计算文本高度
        NSDictionary *dic = @{NSFontAttributeName: [UIFont systemFontOfSize:15]};
        // 预设尺寸  文本最大不会超过这个尺寸
        CGSize size = CGSizeMake(ScreenWidth - 40, 2000);
        CGRect rect = [tempModel.text boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:dic context:nil];
        CGFloat textHeight = rect.size.height + 20;
        if (imgH != 0) {
            return imgH * (ScreenWidth - 40) / imgW + textHeight;
        }else{
            return 0;
        }
    }
}
#pragma mark - cell的点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [self.tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.section == 0) {
        TravelMapViewController *travel = [[TravelMapViewController alloc] init];
        travel.model = self.waypointsArr[indexPath.section][indexPath.row];
        [self.navigationController pushViewController:travel animated:YES];
    }
    if (indexPath.section > 0) {
        
        [UIView animateWithDuration:1 animations:^{
            
            self.collectionView.contentOffset =  CGPointMake(ScreenWidth * (indexPath.row), 0);
            self.navigationController.navigationBarHidden = YES;
            self.tableView.alpha = 0;
            self.collectionView.alpha = 1;
        }];
    }
}
#pragma mark - collection协议方法
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    PicSeeCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"picSeeCell" forIndexPath:indexPath];
    cell.model = self.picSeeArr[indexPath.row];
    return cell;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.picSeeArr.count;
}
#pragma mark - collctionView点击方法
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    [UIView animateWithDuration:1 animations:^{
        self.navigationController.navigationBarHidden = NO;
        self.collectionView.alpha = 0;
        self.tableView.alpha = 1;
    }];
}
#pragma mark - 跳转地图按钮实现方法
- (void)pushToMapDelegate:(NSIndexPath *)indexPath
{
    TravelMapViewController *travel = [[TravelMapViewController alloc] init];
    travel.model = self.waypointsArr[indexPath.section][indexPath.row];
    NSLog(@"%@", travel.model.latitude);
    NSLog(@"%@", travel.model.longitude);
    
//    [self.navigationController pushViewController:travel animated:YES];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
